package org.springblade.task.job.report.book;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.common.enums.DictBizEnum;
import org.springblade.common.utils.DateUtils;
import org.springblade.modules.booksAnalysis.entity.DailyBookChannelOverviewReport;
import org.springblade.modules.booksAnalysis.service.IDailyBookChannelOverviewReportService;
import org.springblade.modules.booksAnalysis.vo.DailyBookChannelOverviewReportVO;
import org.springblade.task.base.param.BaseParam;
import org.springblade.task.base.param.BaseUserClickLogParam;
import org.springblade.task.base.param.BaseUserReadingDataLogParam;
import org.springblade.task.base.service.IBaseEbookInfoService;
import org.springblade.task.base.service.IBaseUserClickLogService;
import org.springblade.task.base.service.IBaseUserReadingDataLogService;
import org.springblade.task.base.vo.BaseEbookInfoVO;
import org.springblade.task.base.vo.BaseUserClickLogVO;
import org.springblade.task.base.vo.BaseUserReadingDataLogVO;
import org.springblade.task.job.base.BaseTaskInfoJob;
import org.springblade.task.quartz.entity.QuartzTask;
import org.springblade.task.quartz.service.IQuartzTaskService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @Title: 书籍渠道概况
 * @version V1.0
 */
@Component
public class DailyBookChannelOverviewReportJob {
	private static Logger logger = LoggerFactory.getLogger(BaseTaskInfoJob.class);

	@Autowired
	private IQuartzTaskService quartzTaskService;
	// 书籍基本信息
	@Autowired
	private IBaseEbookInfoService baseEbookInfoService;
	// 用户阅读日志
	@Autowired
	private IBaseUserReadingDataLogService baseUserReadingDataLogService;
	// 用户点击日志
	@Autowired
	private IBaseUserClickLogService baseUserClickLogService;
	// 每日渠道书籍概况
	@Autowired
	private IDailyBookChannelOverviewReportService dailyBookChannelOverviewReportService;

	/**
	 * 1、简单任务示例（Bean模式）
	 */
	@XxlJob("dailyBookChannelOverviewReportJob")
	public ReturnT<String> dailyBookChannelOverviewReportJob(String param) throws Exception {
		System.out.println(DateUtils.currentDateTime() + " -- XXL-JOB, Hello World.");
		System.err.println("执行静态定时任务日期: " + DailyBookChannelOverviewReportJob.class.getSimpleName());
		QuartzTask quartzTask = quartzTaskService.queryByTaskName(DailyBookChannelOverviewReportJob.class.getSimpleName(), -7);
		// 今日
		String todayDate = DateUtils.crutDate();
		String taskDate = quartzTask.getTaskDate();
		while (taskDate.compareTo(todayDate) < 0) {
			// 当时间大于5点，跳出执行
//			if (DateUtils.getHour24() > 5) {
//				break;
//			}
			// 再加一个凌晨1点判断
			currMethod(taskDate);
			// 增加1天
			taskDate = DateUtils.dateAddDay(taskDate, 1);
		}
		quartzTask.setTaskDate(taskDate);
		quartzTaskService.saveQuartzTask(quartzTask);
		return ReturnT.SUCCESS;
	}

	/**
	 *
	 * @param taskDate
	 */
	public void currMethod(String taskDate) {

		String startTime = DateUtils.getDateStartTime(taskDate);
		String endTime = DateUtils.getDayEndTime(taskDate);
		// 今日之前全部书籍数据
		BaseParam baseParam = new BaseParam();
		baseParam.setToday(endTime);
		List<BaseEbookInfoVO> ebookInfoVOList =  baseEbookInfoService.queryEbookList(baseParam);
		Map<Long, BaseEbookInfoVO> ebookInfoMap = new HashMap<>();
		for(BaseEbookInfoVO ebookInfoVO: ebookInfoVOList) {
			ebookInfoMap.put(ebookInfoVO.getEbookId(), ebookInfoVO);
		}

		// 今日：用户阅读书籍日志数据
		BaseUserReadingDataLogParam param = new BaseUserReadingDataLogParam();
		param.setStartDate(startTime);
		param.setEndDate(endTime);
		List<BaseUserReadingDataLogVO> readingDataLogVOList = baseUserReadingDataLogService.queryChannelReadBookLengthData(param);
		Map<String, BaseUserReadingDataLogVO> readingDataLogMap= new HashMap<>();
		for(BaseUserReadingDataLogVO readingDataLogVO: readingDataLogVOList) {
			readingDataLogMap.put(readingDataLogVO.getBookId() + "-" + readingDataLogVO.getOs(), readingDataLogVO);
		}

		// 今日：用户点击日志
		BaseUserClickLogParam logParam = new BaseUserClickLogParam();
		logParam.setStartDate(startTime);
		logParam.setEndDate(endTime);
		logParam.setVFrom(2); // 2或者5 大于0就行
		List<BaseUserClickLogVO> userClickLogVOList = baseUserClickLogService.queryUserClickLogBookList(logParam);
		Map<String, DailyBookChannelOverviewReportVO> bookChannelOverviewReportMap = new HashMap<>();
		for(BaseUserClickLogVO clickLogVO: userClickLogVOList) {
			long ebookId = clickLogVO.getResId();
			String os = clickLogVO.getOs();
			BaseEbookInfoVO ebookInfoVO = ebookInfoMap.get(ebookId);
			if(null == ebookInfoVO) {
				continue;
			}
			String key = ebookId + "-" + os;

			DailyBookChannelOverviewReportVO channelOverviewReportVO = bookChannelOverviewReportMap.get(key);
			if(null == channelOverviewReportVO) {
				channelOverviewReportVO = new DailyBookChannelOverviewReportVO();
			}
			channelOverviewReportVO.setEbookId(ebookId);
			channelOverviewReportVO.setEbookName(ebookInfoVO.getEbookName());
			channelOverviewReportVO.setChannel(os);
			// 点击进入书详页: 商详PV 、 商详UV
			if(DictBizEnum.CLICK_TYPE_BOOK_DETAILS.getValue() == clickLogVO.getClickType()) {
				channelOverviewReportVO.setBusinessDetailsPv(channelOverviewReportVO.getBusinessDetailsPv() + 1); // 商详PV
				Set<String> businessDetailsUser = channelOverviewReportVO.getBusinessDetailsUser();
				if(businessDetailsUser == null) {
					businessDetailsUser = new HashSet<>();
				}
				businessDetailsUser.add(clickLogVO.getPin());
				channelOverviewReportVO.setBusinessDetailsUser(businessDetailsUser);
				channelOverviewReportVO.setBusinessDetailsUv(businessDetailsUser.size()); //商详UV
			}
			// 立即阅读-> 试读 : 试读次数 、试读人数
			else if(DictBizEnum.CLICK_TYPE_READ_NOW.getValue() == clickLogVO.getClickType()) {
				channelOverviewReportVO.setTryReadNum(channelOverviewReportVO.getTryReadNum() + 1); // 试读次数
				Set<String> tryReadUser = channelOverviewReportVO.getTryReadUser();
				if(tryReadUser == null) {
					tryReadUser = new HashSet<>();
				}
				tryReadUser.add(clickLogVO.getPin());
				channelOverviewReportVO.setTryReadUser(tryReadUser);
				channelOverviewReportVO.setTryReadUserNum(tryReadUser.size()); // 试读人数
			}
			// 加书架： 加书架次数、加书架人数
			else if(DictBizEnum.CLICK_TYPE_ADD_BOOKSHELF.getValue() == clickLogVO.getClickType()) {
				channelOverviewReportVO.setAddBookrackNum(channelOverviewReportVO.getTryReadNum() + 1); // 加书架次数
				Set<String> addBookrackUser = channelOverviewReportVO.getAddBookrackUser();
				if(addBookrackUser == null) {
					addBookrackUser = new HashSet<>();
				}
				addBookrackUser.add(clickLogVO.getPin());
				channelOverviewReportVO.setAddBookrackUser(addBookrackUser);
				channelOverviewReportVO.setAddBookrackUserNum(addBookrackUser.size()); // 加书架人数
			}
			// 加购： 加购次数	、加购人数
			else if(DictBizEnum.CLICK_TYPE_ADDITIONAL_PURCHASE.getValue() == clickLogVO.getClickType()) {
				channelOverviewReportVO.setAddBuyNum(channelOverviewReportVO.getAddBuyNum() + 1); // 加书架次数
				Set<String> addBuyUser = channelOverviewReportVO.getAddBuyUser();
				if(addBuyUser == null) {
					addBuyUser = new HashSet<>();
				}
				addBuyUser.add(clickLogVO.getPin());
				channelOverviewReportVO.setAddBuyUser(addBuyUser);
				channelOverviewReportVO.setAddBuyUserNum(addBuyUser.size()); // 加书架人数
			}
			// 购买次数、人数
			else if(DictBizEnum.CLICK_TYPE_CLICK_TO_BUY.getValue() == clickLogVO.getClickType()) {
				channelOverviewReportVO.setBuyNum(channelOverviewReportVO.getBuyNum() + 1); // 购买次数
				Set<String> buyUser = channelOverviewReportVO.getBuyUser();
				if(buyUser == null) {
					buyUser = new HashSet<>();
				}
				buyUser.add(clickLogVO.getPin());
				channelOverviewReportVO.setBuyUser(buyUser);
				channelOverviewReportVO.setBuyUserNum(buyUser.size()); // 购买人数
			}
			// VIP阅读次数、人数
			else if(DictBizEnum.CLICK_TYPE_VIP_READING.getValue() == clickLogVO.getClickType()) {
				channelOverviewReportVO.setVipReadNum(channelOverviewReportVO.getVipReadNum() + 1); // VIP阅读次数
				Set<String> vipReadUser = channelOverviewReportVO.getVipReadUser();
				if(vipReadUser == null) {
					vipReadUser = new HashSet<>();
				}
				vipReadUser.add(clickLogVO.getPin());
				channelOverviewReportVO.setVipReadUser(vipReadUser);
				channelOverviewReportVO.setVipReadUserNum(vipReadUser.size()); // VIP阅读人数
			}
			// 分享
			else if(DictBizEnum.CLICK_TYPE_SHARE.getValue() == clickLogVO.getClickType()) {
				channelOverviewReportVO.setShareNum(channelOverviewReportVO.getShareNum() + 1); // 分享数
			}

			BaseUserReadingDataLogVO readingDataLogVO = readingDataLogMap.get(key);
			if(null != readingDataLogVO) {
				channelOverviewReportVO.setReadingTime(readingDataLogVO.getLength());
			}
		}

		Iterator iterator = bookChannelOverviewReportMap.keySet().iterator();
		List<DailyBookChannelOverviewReport> channelOverviewReportList = new ArrayList<>();
		DailyBookChannelOverviewReport report = null;
		while (iterator.hasNext()) {
			String key = iterator.next().toString();
			DailyBookChannelOverviewReportVO vo = bookChannelOverviewReportMap.get(key);
			report = new DailyBookChannelOverviewReport();
			BeanUtils.copyProperties(vo, report);
			channelOverviewReportList.add(report);
		}

		dailyBookChannelOverviewReportService.saveBatch(channelOverviewReportList);
	}


	public void init() {
		logger.info("init");
	}

	public void destroy() {
		logger.info("destory");
	}

}
